package main

import (
	"fmt"
	"gitee.com/cajan2/file-process/pkg/filesystem"
	"gitee.com/cajan2/file-process/pkg/util"
	"github.com/urfave/cli"
	"log"
	"os"
	"strings"
)

func main() {
	app := cli.NewApp()

	cli.VersionFlag = cli.BoolFlag{
		Name:  "version, V",
		Usage: "print only the version",
	}
	app.Name = "FileProcess CLI"
	app.Usage = "gitee.com/cajan2/file-process!"
	app.Version = "0.0.1"

	app.UseShortOptionHandling = true
	app.Before = func(*cli.Context) (err error) {
		return
	}
	app.Commands = []cli.Command{
		{
			Name:  "delete_duplicate",
			Usage: "Delete all duplicated content files, options: only dir or only files",
			Flags: []cli.Flag{
				cli.BoolFlag{Name: "fake, f", Usage: "only show duplicated files：仅仅显示重复的文件列表"},
				cli.StringFlag{Name: "dir, d", Usage: "directory:目录"},
				cli.StringFlag{Name: "suffix, s", Usage: "suffix:后缀"},
				cli.StringFlag{Name: "files, i", Usage: "files:文件列表"},
			},
			Action: func(c *cli.Context) (err error) {
				var (
					ignoreFile string
				)
				fake := c.Bool("fake")
				dir := c.String("dir")
				suffix := c.String("suffix")
				files := c.String("files")

				fmt.Println("fake:", fake)
				fmt.Println("dir:", dir)
				fmt.Println("suffix:", suffix)
				fmt.Println("files:", files)
				if dir != "" {
					ignoreFile, _ = filesystem.FindIgnoreFile(dir)
				}
				fmt.Println("ignoreFile:", ignoreFile)
				if fake {
					if size, duplicatedFilesMap, err := filesystem.FindDuplicateFilesWithSameContent(dir, files, suffix,
						ignoreFile); err == nil &&
						duplicatedFilesMap != nil && len(duplicatedFilesMap) > 0 {
						fmt.Printf("size:%d, duplicatedFilesMap:%#v\n", size, duplicatedFilesMap)
					}
				} else {
					if size, deletedFilesMap, err := filesystem.DeleteAllDuplicateContentFiles(dir, files, suffix,
						ignoreFile); err == nil &&
						deletedFilesMap != nil && len(deletedFilesMap) > 0 {
						fmt.Printf("size:%d, deletedFilesMap:%#v\n", size, deletedFilesMap)
					}
				}
				if err != nil {
					fmt.Printf("----delete_duplicate error, dir:%s, error:%s\n", dir, err.Error())
				} else {
					fmt.Println("success")
				}
				return
			},
		},
		{
			Name:  "change_ip",
			Usage: "Change ip in files",
			Flags: []cli.Flag{
				cli.StringFlag{Name: "host_names, o", Usage: "host_names:主机名称列表"},
				cli.StringFlag{Name: "files, i", Usage: "files:文件列表"},
			},
			Action: func(c *cli.Context) (err error) {
				var (
					ipAddress string
					err2      error
				)
				hostNames := strings.TrimSpace(c.String("host_names"))
				files := strings.TrimSpace(c.String("files"))

				fmt.Println("hostNames:", hostNames)
				fmt.Println("files:", files)
				hostNameList := strings.Split(hostNames, ",")
				fileNameList := strings.Split(files, ",")
				if ipAddress, err2 = util.GetIpAddress(); err2 == nil && ipAddress != "" {
					fmt.Printf("GetIpAddress:%s\n", ipAddress)
					// to replace ipaddress in files(comment first then add new)
					for _, fileName := range fileNameList {
						for _, hostName := range hostNameList {
							fmt.Printf("fileName:%s,hostName:%s\n", fileName, hostName)
							var (
								resultDocs map[int]string
							)
							if resultDocs, err2 = filesystem.CommentFileContent(fileName, hostName, ipAddress); err2 == nil {
								if resultDocs != nil && len(resultDocs) > 0 {
									//如果有内容被注释掉，说明需要添加新的ip address，否则默认为原先的ip address已经是最新的了，不需要替换
									content := ipAddress + " " + hostName
									if err2 := filesystem.AppendContent2File(fileName, content); err2 != nil {
										fmt.Printf("AppendContent2File fail,fileName:%s,content:%s,error:%s\n",
											fileName, content, err2.Error())
										return
									}
								} else {
									fmt.Printf("ignored because ip address is latest,fileName:%s,"+
										"ipAddress:%s,hostName:%s\n", fileName, ipAddress, hostName)
								}
							} else {
								fmt.Printf("CommentFileContent fail,fileName:%s,ipAddress:%s,hostName:%s, "+
									"error:%s\n", fileName, ipAddress, hostName, err2.Error())
								return
							}
						}
					}
				}
				if err2 != nil {
					fmt.Printf("----change_ip error, ipAddress:%s, error:%s\n", ipAddress, err2.Error())
				} else {
					fmt.Println("success")
				}
				return
			},
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}
